package com.nanyang.tms.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.nanyang.common.core.dict.CommonEnum;
import com.nanyang.tms.common.exception.TmsManagerException;
import lombok.extern.slf4j.Slf4j;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

@Slf4j
public class BarcodeUtils {
    /**
     * 生成条形码文件
     *
     * @param msg  条形码的文本内容
     * @param path 生成条形码的文件路径
     * @return
     */
    public static String generateFile(String msg, String path) {
        generateBarCode128(msg, path);
        Base64.Encoder encoder = Base64.getMimeEncoder();
        String str = encoder.encodeToString(FileUtil.readBytes(path));
        FileUtil.del(path);
        return str;
    }

    /**
     * 生成code128条形码
     */
    public static void generateBarCode128(String message, String path) {
        OutputStream outputStream=null;
        try {
            outputStream = new FileOutputStream(path);
            Code128Bean bean = new Code128Bean();
            // 分辨率，越大条形码就越大
            int dpi = 150;
            // 设置两侧是否留白
            bean.doQuietZone(true);
            // 设置条形码高度和宽度
            bean.setBarHeight(10);
            bean.setModuleWidth(0.3);
            // 设置文本位置（包括是否显示）
            bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
            // 设置图片类型
            String format = "image/png";
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);
            // 生产条形码
            bean.generateBarcode(canvas, message);
            canvas.finish();
        } catch (IOException e) {
            log.error("异常发生错误码：{} ，错误信息：{}", CommonEnum.SYSTEM_EXCEPTION.getCode(), e);
            throw new TmsManagerException(CommonEnum.SYSTEM_EXCEPTION.getCode(),CommonEnum.SYSTEM_EXCEPTION.getMessage(),e.getMessage());
        }finally {
            IoUtil.close(outputStream);
        }
    }

    public static void main(String[] args) {
        String msg = "TRO2022032300000400301";
        String path = "C:\\Users\\lv\\Desktop\\项目\\new\\条形码\\img.png";
        System.out.println(generateFile(msg, path));
    }
}
